package com.zhongshengnetwork.rightbe.lang.view;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.Constant.LetterConstant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DateUtil;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.customview.PublishSelectPicPopupWindow;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbmodel.NotifydbModel;
import com.zhongshengnetwork.rightbe.dbservice.LetterdbService;
import com.zhongshengnetwork.rightbe.dbservice.NotifydbService;
import com.zhongshengnetwork.rightbe.gsonmodel.ClassifyModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.DryCommentModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuContentDetailModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuInfoDetailModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.BestLangActivity;
import com.zhongshengnetwork.rightbe.lang.activity.CommonLangActivity;
import com.zhongshengnetwork.rightbe.lang.activity.ContactUSActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangCommentActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangDetailActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SmartRankActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SmartRankSettingsActivity;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.letter.activity.LetterConversationActivity;
import com.zhongshengnetwork.rightbe.letter.activity.LetterSettingActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.ClassifyAuthRequestActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTContentActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTListOfClassifyActivity;
import com.zhongshengnetwork.rightbe.wzt.model.WZTUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MsgFragment extends BaseAnalyticsFragment {

    private static final int REQUEST_PUBLISH = 1002;
    private int pageindex = 0;
    private static final int Records = 20;
    public int dataType = 0;
    private List<NotifydbModel> list;
    private ListView listview;
    private int opIndex = 0;
    private boolean isHasMore = false;
    private boolean isRead = false;
    private MyAdapter adapter = null;
    private View rootView;//缓存Fragment view
    private PublishSelectPicPopupWindow menuWindow;
    private List<String> names;

    private AVLoadingIndicatorView avi;

    private RefreshLayout mRefreshLayout;
    private RelativeLayout about_weiju_layout;
    private RelativeLayout about_contact_layout;
    private TextView new_update_circle;

    private RelativeLayout message;

    private List<String> messageIds;

    public MsgHomeFragment msgHomeFragment = null;

    private ImageView no_data_img;

    public void goToTop(){
        if (listview != null){
            listview.setSelection(0);
        }
    }

    public void updateSXTip(int count){
        Log.e("TAG", "count="+count);
        if (new_update_circle != null){
            if (count > 0){
                new_update_circle.setVisibility(View.VISIBLE);
            }else {
                new_update_circle.setVisibility(View.INVISIBLE);
            }
        }


    }

    public void showMenu(View view){
        if (getActivity() == null){
            return;
        }
        if (names == null){
            names = new ArrayList<String>();
        }
        if (itemsOnClick == null){
            return;
        }

        names.clear();
        names.add("全部标注为已读");
        names.add("删除全部");
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : names){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        String title = names.get(which-1);
                        if (title.equals("全部标注为已读")){
                            dealOp(title);
                        }else if (title.equals("删除全部")){
                            dealOp(title);
                        }
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.messageflagment, container, false);
            avi = (AVLoadingIndicatorView)rootView.findViewById(R.id.avi);
            no_data_img = (ImageView) rootView.findViewById(R.id.no_data_img);
            about_weiju_layout = (RelativeLayout) rootView.findViewById(R.id.about_weiju_layout);
            about_weiju_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            about_weiju_layout.setClickable(true);
            about_weiju_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getActivity() != null){

                        //是否开通私信
                        if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(LetterConstant.SXStateKey, false) == false){
                            Intent intent = new Intent(getActivity(), LetterSettingActivity.class);
                            startActivity(intent);
                            return;
                        }

                        Intent wIntent = new Intent(getActivity(), LetterConversationActivity.class);
                        startActivity(wIntent);
                    }
                }
            });
            new_update_circle = (TextView) rootView.findViewById(R.id.new_update_circle);
            if (CommonUtils.isLogin() == true){
                long count = LetterdbService.getAllUnReadCount(CustomApplication.loginModel.getUid());
                updateSXTip((int)count);
            }

            about_contact_layout = (RelativeLayout) rootView.findViewById(R.id.about_contact_layout);
            about_contact_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            about_contact_layout.setClickable(true);
            about_contact_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getActivity() != null){
                        Intent intent = new Intent(getActivity(), ContactUSActivity.class);
                        startActivity(intent);
                    }
                }
            });

            LinearLayout top_item_layout = (LinearLayout) rootView.findViewById(R.id.top_item_layout);
            top_item_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            if (dataType != Integer.valueOf(Constant.MessageListType.NotifyMsgType)){
                RelativeLayout about_weiju_layout = (RelativeLayout) rootView.findViewById(R.id.about_weiju_layout);
                about_weiju_layout.setVisibility(View.GONE);
                LinearLayout message_line1 = (LinearLayout) rootView.findViewById(R.id.message_line1);
                message_line1.setVisibility(View.GONE);

                RelativeLayout about_contact_layout = (RelativeLayout) rootView.findViewById(R.id.about_contact_layout);
                about_contact_layout.setVisibility(View.GONE);
            }

            RelativeLayout ordertype_layout = (RelativeLayout) rootView.findViewById(R.id.ordertype_layout);
            ordertype_layout.setClickable(true);
            ordertype_layout.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
            ordertype_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showMenu(view);
                }
            });

            ImageView publish_img = (ImageView) rootView.findViewById(R.id.publish_img);
            publish_img.setClickable(true);
            publish_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showMenu(view);
                }
            });

            if (names == null){
                names = new ArrayList<String>();
            }
            if (list == null){
                list = new ArrayList<NotifydbModel>();
            }
            listview=(ListView) rootView.findViewById(R.id.message_listview);
            adapter = new MyAdapter();
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (getActivity() == null || list == null || list.size() == 0){
                        return;
                    }
                    int index = position;// - 1;
                    while (index < 0){//解决部分手机点击第一条不是从1开始的问题
                        index+=1;
                    }

                    NotifydbModel model = list.get(index);
                    if(model.getType() == Integer.valueOf(Constant.MessageType.Life_Result)){
                        //生活圈审核消息
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithLang(dataJson.getString("lifeid"));
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.LifeLike_Result)){
                        //生活圈关注消息
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithCare(dataJson.getString("userid"),"");
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.LifeDZ_Result)
                     || model.getType() == Integer.valueOf(Constant.MessageType.Lang_Banner_Notify)){
                        //生活圈笔芯信息
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);

                            String dataType = "";
                            if (dataJson.has("dataType")){
                                dataType = dataJson.getString("dataType");
                            }
                            if (!CommonUtils.isEmpty(dataType) && dataType.equals("0")){
                                dealWithBestOriginalLang(dataJson.getString("lifeid"), 12);
                            }else if (!CommonUtils.isEmpty(dataType) && dataType.equals("1")){
                                dealWithBestOriginalLang(dataJson.getString("lifeid"), 13);
                            }else {
                                dealWithLang(dataJson.getString("lifeid"));
                            }

                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.LifeC_Result)){
                        //生活圈评论信息
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithLang(dataJson.getString("lifeid"));
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.LifeCR_Result)){
                        //生活圈评论回复
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithComment(dataJson.getString("commentid"),dataJson.getString("lifeid"));
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.LifeCL_Result)
                     || model.getType() == Integer.valueOf(Constant.MessageType.Comment_Collection_Notify)){
                        //生活圈评论笔芯
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithComment(dataJson.getString("commentid"),dataJson.getString("lifeid"));
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.LangPrize_Result)){
                        //微句获奖通知
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithCare(8);
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.SelfInfo)){
                        //系统通知
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            String content = dataJson.getString("content");
                            if (getActivity() == null){
                                return;
                            }
                            if (dataJson.getString("type").equals("0")){
                                //文字说明
                                if (!CommonUtils.isEmpty(content)){
                                    final CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
                                    builder.setTitle("系统通知");
                                    builder.setMessage(content);
                                    builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    });
                                    CustomDialog dialog = builder.create();
                                    dialog.show();
                                }
                            }else if (dataJson.getString("type").equals("1")){
                                //微句推荐
                                if (!CommonUtils.isEmpty(content)){
                                    //dealWithLang(content);

                                    String dataType = "";
                                    if (dataJson.has("dataType")){
                                        dataType = dataJson.getString("dataType");
                                    }
                                    if (!CommonUtils.isEmpty(dataType) && dataType.equals("0")){
                                        dealWithBestOriginalLang(content, 12);
                                    }else if (!CommonUtils.isEmpty(dataType) && dataType.equals("1")){
                                        dealWithBestOriginalLang(content, 13);
                                    }else {
                                        dealWithLang(content);
                                    }

                                }
                            }else if (dataJson.getString("type").equals("2")){
                                //评论推荐
                                if (!CommonUtils.isEmpty(content)){
                                    dealWithComment(content,"");
                                }
                            }else if (dataJson.getString("type").equals("3")){
                                //链接推荐
                                if (!CommonUtils.isEmpty(content)){
                                    Intent webIntent = new Intent(getActivity(), MyWebActivity.class);
                                    webIntent.putExtra(APIKey.urlKey, content);
                                    startActivity(webIntent);
                                }
                            }else if (dataJson.getString("type").equals("4")){
                                dealWithWZT(content,0);
                            }

                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.Contact_Result)){
                        //系统反馈
                        if (model.getState() == 0){
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                        }

                        Intent intent = new Intent(getActivity(), ContactUSActivity.class);
                        startActivity(intent);
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.WeiShu_Like_Notify)){
                        //微纸条点赞通知
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            String selectIndex = "";
                            if (dataJson.has("selectIndex")){
                                selectIndex = dataJson.getString("selectIndex");
                            }
                            if (!CommonUtils.isEmpty(selectIndex)){
                                dealWithWZT(dataJson.getString("weishuid"),Integer.valueOf(selectIndex));
                            }else {
                                dealWithWZT(dataJson.getString("weishuid"),2);
                            }
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.WeiShu_Comment_Notify)){
                        //微纸条评论通知
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithWZT(dataJson.getString("weishuid"),1);
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.WeiShu_Subscribe_Notify)){
                        //微纸条订阅通知
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithWZT(dataJson.getString("weishuid"),3);
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.WeiShu_Content_Notify)

                    || model.getType() == Integer.valueOf(Constant.MessageType.Weishu_Content_C_Notify)){
                        //微纸条内容点赞、分享、评论、收藏通知
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithWZTContent(dataJson.getString("sourceid"));
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.WeiShu_Content_Comment_Notify)){
                        //微纸条评论点赞、回复、收藏通知
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithWZTComment(dataJson.getString("commentid"));
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.Classify_Request_Notify)){
                        model.setState(1);
                        list.set(index,model);
                        adapter.notifyDataSetChanged();
                        NotifydbService.saveOrUpdate(model);
                        Intent intent = new Intent(getActivity(), ClassifyAuthRequestActivity.class);
                        startActivity(intent);
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.Classify_Authed_Notify)){
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithClassify(dataJson.getString("classifyId"));
                        }catch (Exception e){

                        }
                    }else if (model.getType() == Integer.valueOf(Constant.MessageType.Rank_Smart_Notify)){
                        try {
                            JSONObject dataJson = CommonUtils.stringToJson(model.getDict());
                            model.setState(1);
                            list.set(index,model);
                            adapter.notifyDataSetChanged();
                            NotifydbService.saveOrUpdate(model);
                            dealWithSmartRank(dataJson);
                        }catch (Exception e){

                        }
                    }
                    updateMsgCount();
                    if (msgHomeFragment != null){
                        msgHomeFragment.updateTitleByType(dataType);
                    }
                }
            });
            listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    if (getActivity() == null || list == null || list.size() == 0){
                        return true;
                    }
                    if (names == null){
                        names = new ArrayList<String>();
                    }
                    if (itemsOnClick == null){
                        return true;
                    }
                    opIndex = position;//-1;
                    names.clear();
                    names.add("删除");
                    ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                            .builder()
                            .setTitle("请选择")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true);
                    for (String s : names){
                        actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (which > 0){
                                    String title = names.get(which-1);
                                    if (title.equals("删除")){
                                        dealOp(title);
                                    }
                                }
                            }
                        });
                    }
                    actionSheetDialog.show();

                    return true;
                }
            });

            mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(true);//启用刷新
            mRefreshLayout.setEnableLoadMore(true);//启用加载
            //刷新
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    //refreshlayout.finishRefresh();
                    getData();
                }
            });
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    //refreshLayout.finishLoadMore();
                    loadMore();
                }
            });

            message = (RelativeLayout) rootView.findViewById(R.id.message);
            message.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            TextView notify_listview_item_title1 = (TextView) rootView.findViewById(R.id.notify_listview_item_title1);
            notify_listview_item_title1.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            LinearLayout message_line1 = (LinearLayout) rootView.findViewById(R.id.message_line1);
            message_line1.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

            LinearLayout message_bg = (LinearLayout) rootView.findViewById(R.id.message_bg);
            message_bg.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

            TextView notify_listview_item_title2 = (TextView) rootView.findViewById(R.id.notify_listview_item_title2);
            notify_listview_item_title2.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

            LinearLayout message_line2 = (LinearLayout) rootView.findViewById(R.id.message_line2);
            message_line2.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

            listview.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            listview.setDivider(new ColorDrawable(AppThemeUtils.getInstance().getBackgroundColor()));
            listview.setDividerHeight(ScreenUtils.dip2px(getActivity(), 1));

            getData();
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    }

    //加载更多
    private void loadMore(){
        if (getActivity() == null){
            return;
        }
        pageindex += 1;
        List<NotifydbModel> ll = NotifydbService.getDataByType(CustomApplication.loginModel.getUid(),pageindex,Records,dataType);
        final List<NotifydbModel> l = ll;
        if (l != null && l.size() > 0){
            mRefreshLayout.setEnableLoadMore(true);
            list.addAll(l);
            //listview.stopLoadMore();
            mRefreshLayout.finishLoadMore();
            adapter.notifyDataSetChanged();
        }else {
            //listview.setPullLoadEnable(false);
            mRefreshLayout.finishLoadMore();
            mRefreshLayout.setEnableLoadMore(false);
        }
    }

    public void getFirstData(){
        if (getActivity() == null){
            return;
        }
        if (pageindex == 0 && list != null && list.size() == 0){
            getData();
        }
    }

    public void getLatest(){
        if (getActivity() == null){
            return;
        }
        if (listview == null){
            return;
        }
        new Thread(){
            @Override
            public void run() {
                super.run();
                List<NotifydbModel> ll = NotifydbService.getDataByType(CustomApplication.loginModel.getUid(),0,Records,dataType);
                final List<NotifydbModel> l = ll;
                if (getActivity() == null){
                    return;
                }
                if(l != null && l.size() > 0){

                    List<NotifydbModel> lt = new ArrayList<NotifydbModel>();
                    if (messageIds == null){
                        messageIds = new ArrayList<>();
                    }
                    for (NotifydbModel n : l){
                        if (messageIds.contains(n.getId()+"") == false){
                            messageIds.add(n.getId()+"");
                            lt.add(n);
                        }

                    }

                    if (lt.size() == 0){
                        return;
                    }

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (list == null){
                                list = new ArrayList<NotifydbModel>();
                                list.addAll(lt);
                            }else {
                                list.addAll(0, lt);
                            }
                            adapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        }.start();
    }

    public void getData(){
        if (getActivity() == null){
            return;
        }
        pageindex = 0;
        if (listview == null){
            return;
        }

        new Thread(){
            @Override
            public void run() {
                super.run();
                List<NotifydbModel> ll = NotifydbService.getDataByType(CustomApplication.loginModel.getUid(),pageindex,Records,dataType);
                final List<NotifydbModel> l = ll;
                if (getActivity() == null){
                    return;
                }
                if(l != null && l.size() > 0){

                    if (messageIds == null){
                        messageIds = new ArrayList<>();
                    }else {
                        messageIds.clear();
                    }
                    for (NotifydbModel n : l){
                        messageIds.add(n.getId()+"");
                    }

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (list == null){
                                list = new ArrayList<NotifydbModel>();
                            }else {
                                list.clear();
                            }
                            no_data_img.setVisibility(View.INVISIBLE);
                            list.addAll(l);
                            if (l.size() > 0){
                                isHasMore = true;
                                //listview.setPullLoadEnable(true);
                                mRefreshLayout.setEnableLoadMore(true);
                            }else {
                                isHasMore = false;
                                //listview.setPullLoadEnable(false);
                                mRefreshLayout.setEnableLoadMore(false);
                            }
                            mRefreshLayout.finishRefresh();
                            adapter.notifyDataSetChanged();
                        }
                    });
                }else {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            isHasMore = false;
                            if (list == null){
                                list = new ArrayList<NotifydbModel>();
                            }else {
                                list.clear();
                            }
                            adapter.notifyDataSetChanged();
                            no_data_img.setVisibility(View.VISIBLE);
                            mRefreshLayout.setEnableLoadMore(false);
                            mRefreshLayout.finishRefresh();
                        }
                    });
                }
            }
        }.start();

    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.notify_listview_item,null);
            }
            View view=convertView;

            RelativeLayout notify_layout = (RelativeLayout) view.findViewById(R.id.notify_layout);
            notify_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

            if (no_data_img.getVisibility() == View.VISIBLE){
                no_data_img.setVisibility(View.INVISIBLE);
            }

            //view= LayoutInflater.from(getActivity()).inflate(R.layout.notify_listview_item, null);
            TextView title = (TextView) view.findViewById(R.id.notify_listview_item_title);
            TextView time = (TextView) view.findViewById(R.id.notify_listview_item_time);
            NotifydbModel model = list.get(position);
            title.setText(model.getContent());
            time.setText(DateUtil.getChatDate(model.getTime()));
            if (isRead == true){
                title.setTextColor(AppThemeUtils.getInstance().getReadMessageTextColor());
                time.setTextColor(AppThemeUtils.getInstance().getReadMessageTextColor());
            }else {
                if (model.getState() == 0){//未读
                    title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
                    time.setTextColor(getResources().getColor(R.color.defaultSmallFontColor));
                }else {//已读
                    title.setTextColor(AppThemeUtils.getInstance().getReadMessageTextColor());
                    time.setTextColor(AppThemeUtils.getInstance().getReadMessageTextColor());
                }
            }

            return view;
        }
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener(){

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.first_button:
                    dealOp(names.get(0));
                    break;
                case R.id.second_button:
                    dealOp(names.get(1));
                    break;
                case R.id.third_button:
                    dealOp(names.get(2));
                    break;
                default:

                    break;
            }

        }

    };

    public void dealOp(String name){
        if (getActivity() == null){
            return;
        }


        if (name.equals("删除全部")){
            NotifydbService.deleteAllByType(CustomApplication.loginModel.getUid(),dataType);
            list.clear();
            adapter.notifyDataSetChanged();
            if (msgHomeFragment != null){
                msgHomeFragment.updateTitleByType(dataType);
            }
            updateMsgCount();
        }else if (name.equals("删除")){
            NotifydbModel model = list.get(opIndex);
            NotifydbService.deleteById(model.getId());
            list.remove(model);
            adapter.notifyDataSetChanged();
            if (msgHomeFragment != null){
                msgHomeFragment.updateTitleByType(dataType);
            }
            updateMsgCount();
        }else if (name.equals("全部标注为已读")){
            long count = NotifydbService.getUnReadCountByType(CustomApplication.loginModel.getUid(), dataType);

            if (count < 1){
                return;
            }
            new Thread(){
                @Override
                public void run() {
                    super.run();

                    NotifydbService.changeToReadStateByType(CustomApplication.loginModel.getUid(), dataType);
                    if (list != null && list.size() > 0){
                        for (NotifydbModel model : list){
                            model.setState(1);
                        }
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                            if (msgHomeFragment != null){
                                msgHomeFragment.updateTitleByType(dataType);
                            }
                            updateMsgCount();
                        }
                    });
                }
            }.start();
        }
    }

    private void dealWithBestOriginalLang(String langid, int type){
        if (getActivity() == null){
            return;
        }
        avi.show();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, langid);
        map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        String url = "miniapp/langappid/getlanginfo.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                if (getActivity() == null){
                    return;
                }
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    LangInfoModel langInfoModel = GsonTools.getLangInfoModel(data);

                    langInfoModel.setIscare(true);
                    if (langInfoModel.getStatus() == 1 || langInfoModel.getStatus() == 4){
                        Intent intent = new Intent(getActivity(), CommonLangActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", langInfoModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        intent.putExtra("type", type);
                        startActivity(intent);
                    }else if(langInfoModel.getStatus() == 2 ){
                        Intent intent = new Intent(getActivity(), LangPublishActivity.class);
                        if (!CommonUtils.isEmpty(langInfoModel.getImg())){
                            ArrayList<String> l = new ArrayList<String>();
                            List<String> ll = CommonUtils.stringToArrayList(langInfoModel.getImg());
                            l.addAll(ll);
                            intent.putStringArrayListExtra("img", l);
                        }
                        intent.putExtra("isRepublish",true);
                        intent.putExtra("content",langInfoModel.getTitle());
                        intent.putExtra("langid",langInfoModel.getLangid());
                        intent.putExtra("status",langInfoModel.getStatus());
                        intent.putExtra("type",langInfoModel.getType());
                        intent.putExtra("typename",langInfoModel.getTypename());
                        getActivity().startActivityForResult(intent, REQUEST_PUBLISH);
                    }
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    private void dealWithLang(String langid){
        if (getActivity() == null){
            return;
        }
        avi.show();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, langid);
        map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        String url = "miniapp/langappid/getlanginfo.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                if (getActivity() == null){
                    return;
                }
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    LangInfoModel langInfoModel = GsonTools.getLangInfoModel(data);

                    langInfoModel.setIscare(true);
                    if (langInfoModel.getStatus() == 1 || langInfoModel.getStatus() == 4){
                        Intent intent = new Intent(getActivity(), LangDetailActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", langInfoModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        intent.putExtra("latestComment", true);
                        startActivity(intent);
                    }else if(langInfoModel.getStatus() == 2 ){
                        Intent intent = new Intent(getActivity(), LangPublishActivity.class);
                        if (!CommonUtils.isEmpty(langInfoModel.getImg())){
                            ArrayList<String> l = new ArrayList<String>();
                            List<String> ll = CommonUtils.stringToArrayList(langInfoModel.getImg());
                            l.addAll(ll);
                            intent.putStringArrayListExtra("img", l);
                        }
                        intent.putExtra("isRepublish",true);
                        intent.putExtra("content",langInfoModel.getTitle());
                        intent.putExtra("langid",langInfoModel.getLangid());
                        intent.putExtra("status",langInfoModel.getStatus());
                        intent.putExtra("type",langInfoModel.getType());
                        intent.putExtra("typename",langInfoModel.getTypename());
                        getActivity().startActivityForResult(intent, REQUEST_PUBLISH);
                    }
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    private void dealWithComment(String commentid, final String langid){
        if (getActivity() == null){
            return;
        }
        avi.show();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, commentid);
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        String url = "miniapp/langappid/commentcontent.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                if (getActivity() == null){
                    return;
                }
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    DryCommentModel model = GsonTools.getCommentModel(data);
                    Intent intent = new Intent(getActivity(), LangCommentActivity.class);
                    intent.putExtra("id",langid);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("DryCommentModel", model);
                    intent.putExtras(bundle);
                    intent.putExtra("way", 0);
                    startActivity(intent);
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    private void dealWithWZT(String id, final int selectIndex){
        if (getActivity() == null){
            return;
        }
        avi.show();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, id);
        map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        String url = "weishu/theme/info.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                if (getActivity() == null){
                    return;
                }
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    WeiShuInfoDetailModel langInfoModel = GsonTools.getWeiShuInfo(data);

                    if (CommonUtils.isLogin() == true && CustomApplication.loginModel.getUid().equals(langInfoModel.getUserid())){
                        Intent intent = new Intent(getActivity(), WZTActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", langInfoModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        intent.putExtra("selectIndex",selectIndex);
                        startActivity(intent);
                    }else {
                        WZTUtils.goToWZT(getActivity(),langInfoModel);
                    }
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    private void dealWithWZTContent(String langid){
        if (getActivity() == null){
            return;
        }
        avi.show();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, langid);
        map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        String url = "weishu/content/info.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                if (getActivity() == null){
                    return;
                }
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    WeiShuContentDetailModel langInfoModel = GsonTools.getWeiShuContentDetailModel(data);
                    Intent intent = new Intent(getActivity(), WZTContentActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("model", langInfoModel);//序列化
                    intent.putExtras(bundle);//发送数据
                    intent.putExtra("latestComment", true);
                    startActivity(intent);
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    private void dealWithWZTComment(String commentid){
        if (getActivity() == null){
            return;
        }
        avi.show();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, commentid);
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        String url = "weishu/theme/comment/detail.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                if (getActivity() == null){
                    return;
                }
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    DryCommentModel model = GsonTools.getCommentModel(data);
                    Intent intent = new Intent(getActivity(),LangCommentActivity.class);
                    intent.putExtra("id",model.getSourceid());
                    intent.putExtra("type",1);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("DryCommentModel", model);
                    intent.putExtras(bundle);
                    intent.putExtra("way", 0);
                    startActivity(intent);
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    private void dealWithClassify(String classifyId){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("dataId", classifyId);
        if (CommonUtils.isLogin() == true){
            map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        }
        String url = "weishu/classify/info.do";
        avi.show();
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    ClassifyModel model = GsonTools.getClassifyModelOne(data);
                    if (GsonTools.getClassifyNeedAuth(data) == true){
                        ToastUtil.show(getActivity(), "分类已删除或者被取消查看权限");
                    }else {
                        Intent intent = new Intent(getActivity(), WZTListOfClassifyActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("model",model);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }else{
                    ToastUtil.show(getActivity(), "分类已删除或者被取消查看权限");
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    private void dealWithCare(int index){
        if (getActivity() == null){
            return;
        }
        Log.e("TAG","发送通知");
        //进入个人中心
        Intent mIntent = new Intent(BroadcastDefine.Show_My_Action);
        //发送广播
        mIntent.putExtra("index",index);
        CustomApplication.mContext.sendBroadcast(mIntent);
    }

    private void dealWithCare(final String userid, final String nickname){
        if (getActivity() == null){
            return;
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //进入个人主页
                Intent intent = new Intent(getActivity(), UserLangActivity.class);
                intent.putExtra(APIKey.useridKey,userid);
                intent.putExtra(APIKey.typeKey,1);
                intent.putExtra(APIKey.titleKey,CommonUtils.formatString(nickname));
                startActivity(intent);
            }
        });
    }


    private void updateMsgCount(){
        Intent mIntent = new Intent(BroadcastDefine.Update_MsgCount_Action);
        //发送广播
        CustomApplication.mContext.sendBroadcast(mIntent);
    }

    private void dealWithSmartRank(JSONObject dataJson){
        if (getActivity() == null){
            return;
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    String rankid = dataJson.getString("rankid");
                    if (!CommonUtils.isEmpty(rankid)){
                        String type = dataJson.getString("type");
                        if (type.equals("0")){
                            //占领封面
                            if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.Smart_Rank_State, false) == false){
                                Intent intent = new Intent(getActivity(), SmartRankSettingsActivity.class);
                                startActivity(intent);
                            }else {
                                Intent intent = new Intent(getActivity(), SmartRankActivity.class);
                                intent.putExtra("rankid", rankid);
                                intent.putExtra("type", type);
                                startActivity(intent);
                            }
                        }else if (type.equals("1")){
                            //赞了封面
                            //进入个人主页
                            Intent intent = new Intent(getActivity(), UserLangActivity.class);
                            intent.putExtra(APIKey.useridKey,dataJson.getString("userid"));
                            intent.putExtra(APIKey.typeKey,1);
                            intent.putExtra(APIKey.titleKey,CommonUtils.formatString(dataJson.getString("nickname")));
                            startActivity(intent);
                        }else if (type.equals("2")){
                            //赞了排名
                            if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.Smart_Rank_State, false) == false){
                                Intent intent = new Intent(getActivity(), SmartRankSettingsActivity.class);
                                startActivity(intent);
                            }else {
                                Intent intent = new Intent(getActivity(), SmartRankActivity.class);
                                intent.putExtra("rankid", rankid);
                                intent.putExtra("type", type);
                                startActivity(intent);
                            }
                        }
                    }
                }catch (Exception e){

                }
            }
        });

    }

}
